package FunctionsGA;

import java.util.Random;

import Function.Function;
import Function.Function1;
import Function.Function2;
import Function.Function3;
import Function.Function4;
import GA.Chromosome;
import GA.Phenotype;

public class BinaryChromosome extends Chromosome{
	
	private Random myRandom = new Random();
	private Function f;
	
	public BinaryChromosome(Function f, double accuracy){
		this.f = f;
		chromosomeLenght = f.bitLength(accuracy);
		gene = new BinaryGen[chromosomeLenght];	
	}
	
	public void init(){
		for (int i = 0; i < this.getChromosomeLenght(); i++)
			gene[i] = new BinaryGen(myRandom.nextBoolean());
	}
	
	public double evaluate(){
		return f.evaluate(Phenotype.getValue(gene, chromosomeLenght, f)); 
	}

	protected boolean isBetter(Chromosome other) {
		if (f instanceof Function1) return this.aptitude > other.getAptitude();
		if (f instanceof Function2) return this.aptitude > other.getAptitude();
		if (f instanceof Function3) return this.aptitude < other.getAptitude();
		if (f instanceof Function4) return this.aptitude < other.getAptitude();
		return this.aptitude < other.getAptitude();
	}

	public Chromosome clone() {
		BinaryChromosome c = new BinaryChromosome(this.f, 1);
		c.setAptitude(aptitude);
		c.setChromosomeLenght(chromosomeLenght);
		c.setGene(gene.clone());
		c.setScore(score);
		c.setScore_acum(score_acum);
		return c;
	}

	public double[] getPhenotype() {
		return Phenotype.getValue(gene, chromosomeLenght, f);
	}
}
